package com.cts.tmall.app.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cts.tmall.biz.service.OrdService;
import com.cts.tmall.biz.service.PrdService;
import com.cts.tmall.dal.entity.TmallOrd;
import com.cts.tmall.dal.entity.TmallPrd;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/ord")
public class OrdController extends BaseController<TmallOrd>{

    @Autowired
    private OrdService ordService;
    @Autowired
    private PrdService prdService;

    @GetMapping("/page/custom")
    public Map<String, Object> queryOrder(@RequestParam Map params) throws Exception {
        IPage<TmallOrd> page = ordService.queryOrd(params);
        List<Map<String, Object>> records = page.getRecords().stream().map(ord -> {
            Map<String, Object> map = null;
            try {
                map = PropertyUtils.describe(ord);
            } catch (Exception e) {

            }
            TmallPrd prd = prdService.queryById(ord.getPrdNo());
            if (prd != null && map != null) {
                map.put("prd", prd);
            }
            return map;
        }).collect(Collectors.toList());
        return ImmutableMap.<String, Object>builder()
                .put("pageNumb", page.getCurrent())
                .put("pageSize", page.getSize())
                .put("total", page.getTotal())
                .put("data", records)
                .build();
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam Map params, @RequestHeader("User-Agent") String userAgent) throws Exception {
        ImmutableMap<String, String> afterSaleStatusEnums = ImmutableMap.<String, String>builder()
                .put("01", "退货中-用户申请")
                .put("02", "退货中-商家同意退货")
                .put("03", "退货中-客服仲裁")
                .put("04", "已关闭-退货失败")
                .put("05", "退货中-客服同意")
                .put("06", "退货中-用户填写物流")
                .put("07", "退货成功-商户同意")
                .put("08", "退货中-再次客服仲裁")
                .put("09", "退货成功-客服同意")
                .put("10", "退货-用户取消")
                .put("11", "退款成功-售后退款")
                .put("12", "退货中-再次用户申请")
                .put("13", "退货成功-商户已退款")
                .put("14", "退货中-商家拒绝退货")
                .put("15", "退货失败")
                .put("16", "退货中-商家再次拒绝")
                .put("17", "退货中-退款申请")
                .put("18", "退款申请取消")
                .put("19", "退款成功-商家同意")
                .put("20", "退款中-商家拒绝")
                .put("21", "退款中-客服仲裁")
                .put("22", "退款中-客服同意")
                .put("23", "退款中-退款失败")
                .put("24", "已关闭-退款失败")
                .put("25", "退款中-线下退款成功")
                .put("26", "退款中-退款成功").build();
        ImmutableMap<String, String> bizTypeEnums = ImmutableMap.<String, String>builder()
                .put("01", "鲁班广告")
                .put("02", "精选联盟")
                .put("03", "商城")
                .put("04", "自主经营")
                .put("05", "线索广告")
                .put("06", "抖音门店").build();
        ImmutableMap<String, String> payTypeEnums = ImmutableMap.<String, String>builder()
                .put("01", "货到付款")
                .put("02", "在线支付").build();
        ImmutableMap<String, String> ordStatusEnums = ImmutableMap.<String, String>builder()
                .put("01", "待确认/支付")
                .put("02", "备货中")
                .put("03", "已发货")
                .put("04", "已取消")
                .put("05", "已完成").build();


        params.put("pageNumb", "1");
        params.put("pageSize", Integer.toString(Integer.MAX_VALUE));
        IPage<TmallOrd> page = ordService.queryOrd(params);
        List<TmallOrd> records = page.getRecords();

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("订单明细");
        HSSFRow header = sheet.createRow(0);
        header.createCell(0).setCellValue("子订单编号");
        header.createCell(1).setCellValue("商品名称");
        header.createCell(2).setCellValue("单价");
        header.createCell(3).setCellValue("数量");
        header.createCell(4).setCellValue("备注");
        header.createCell(5).setCellValue("售后");
        header.createCell(6).setCellValue("业务类型");
        header.createCell(7).setCellValue("支付方式");
        header.createCell(8).setCellValue("收货信息");
        header.createCell(9).setCellValue("订单状态");
        header.createCell(10).setCellValue("实收款");

        for (int i = 1; i <= records.size(); i++) {
            TmallOrd ord = records.get(i - 1);
            TmallPrd prd = prdService.queryById(ord.getPrdNo());
            HSSFRow row = sheet.createRow(i);
            row.createCell(0).setCellValue(ord.getOrdNo());
            row.createCell(1).setCellValue(prd.getPrdName() + "    " + prd.getPrdSubName());
            row.createCell(2).setCellValue("￥" + prd.getPrdPrice());
            row.createCell(3).setCellValue(ord.getCount());
            row.createCell(4).setCellValue(ord.getOrdDesc());
            row.createCell(5).setCellValue(afterSaleStatusEnums.get(ord.getAfterSaleStatus()));
            row.createCell(6).setCellValue(bizTypeEnums.get(ord.getBizType()));
            row.createCell(7).setCellValue(payTypeEnums.get(ord.getPayType()));
            row.createCell(8).setCellValue(ord.getCustomName() + "    " + ord.getCustomTel());
            row.createCell(9).setCellValue(ordStatusEnums.get(ord.getOrdStatus()));
            row.createCell(10).setCellValue("￥" + ord.getRealPrice());
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wb.write(bos);
        byte[] bytes = bos.toByteArray();
        ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
        builder.contentLength(bytes.length);
        builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        if (userAgent.indexOf("MSIE") > 0) {
            builder.header("Content-Disposition", "attachment; filename=" + URLEncoder.encode("订单明细.xls", "UTF-8"));
        } else {
            builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + URLEncoder.encode("订单明细.xls", "UTF-8"));
        }
        return builder.body(bytes);
    }
}
